<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>新增产品</title>
    <style>
        .row {
            display: flex;
            flex-direction: row;
            margin: 6px;
        }
        .row .label {
            margin-right: 10px;
        }
        .result-area {
            flex-direction: column;
            margin: 6px;
        }
    </style>
</head>
<body>
    <h1>新增产品</h1>
    <div class="row">
        <div class="label">分类：</div>
        <select name="classify" id="classify"></select>
    </div>
    <div class="row">
        <div class="label">链接：</div>
        <input type="text" id="link" name="link" style="width: 300px;">
    </div>
    <div class="row">
        <button id="get-link">粘贴链接</button>
        <button id="start-analysis">开始分析</button>
        <input type="checkbox" id="check-chinese"/>是否检查中国卖家
    </div>
    <div class="row result-area">
        <h2 id="result"></h2>
        <div id="detail"></div>
    </div>
    <script src="{{ url_for('static', path='libs/jquery-3.7.1.min.js') }}"></script>
    <script>
        $.ajax({
            url: '/api/product/get_classify',
            type: 'GET',
            success: function (data) {
                var classify = data.data;
                console.log(classify);
                var select = $('select[name="classify"]');
                for (var i = 0; i < classify.length; i++) {
                    var option = $('<option value="' + classify[i].id + '">' + classify[i].name + '</option>');
                    select.append(option);
                }
            }
        })

        $('#start-analysis').click(function () {
            $('#result').text('收录中...')
            $('#detail').text('')
            $.ajax({
                url: '/api/product/add_product',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    classify: $('#classify').val(),
                    url: $('#link').val(),
                    checkChinese: $('#check-chinese').prop('checked')
                }),
                success: function (data) {
                    $('#result').text('采集成功');
                    $('#detail').html('品牌：' + data.data.brand + '<br /> 分类：' + data.data.classify + '<br /> 编号：' + data.data.code + '<br /> 评分：' + data.data.star + '<br /> 评论数：' + data.data.comment_num + '<br /> 是否中国卖家：' + data.data.is_chinese_seller + '<br /> 发货渠道：' + data.data.ship_from)
                },
                error: function (xhr, status, error) {
                    data = xhr.responseJSON;
                    $('#result').text(data.status_code + ' - ' + data.message);
                }
            })
        })
        $('#get-link').click(async () =>  {
            const url = await navigator.clipboard.readText();
            $('#link').val(url)
        })
    </script>
</body>
</html>